<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>绘制圆弧</title>
</head>
<body>

    <canvas height="600" width="800" id="canvas">

    </canvas>

    <script>

        function radian(deg) {
            return deg * Math.PI / 180;
        }

        function deg(radian) {
            return radian * 180 / Math.PI;
        }

        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');

        // ctx.moveTo(200, 200);
        // ctx.arc(200, 200, 100, 0, 270 * Math.PI / 180);
        // ctx.closePath();
        // ctx.stroke();

        // 做一个饼状图
        const data = [
            { value: 3, color: '#f22', title: '讲师' },
            { value: 1, color: '#a44', title: '教授' },
            { value: 2, color: 'green', title: '副教授' },
            { value: 5, color: 'purple', title: '工程师' },
        ];

        const TOTAL = data.reduce((acc, item) => {
            return acc + item.value;
        }, 0);

        //绘制：
        let startAngle = 0;
        for(let i = 0;i < data.length;i ++) {
            let percent = data[i].value / TOTAL;
            let item = data[i];
            let degAngle = percent * 360;
            ctx.beginPath();
            ctx.moveTo(300, 300);
            // 上一次的开始角度加上这次的“新增角度”，等于结束的角度
            let endAngle = startAngle + radian(degAngle);

            ctx.arc(300, 300, 100, startAngle, endAngle);
            ctx.fillStyle = item.color;
            ctx.fill();

            // 绘制文字
            ctx.beginPath();
            ctx.font = "14px '微软雅黑'";
            let textAngle = deg((startAngle + endAngle) / 2);
            // 如果角度在 [90 - 270] 度之间，就让文本对齐方式是 end
            if(textAngle > 90 && textAngle <= 270) {
                ctx.textAlign = 'end';
            }

            let textX = 300 + 110 * Math.cos(radian(textAngle));
            let textY = 300 + 110 * Math.sin(radian(textAngle));
            ctx.fillStyle = '#000';
            ctx.fillText(item.title + ' ' + (percent * 100).toFixed(1) + '%', textX, textY);

            startAngle = endAngle;
        }

    </script>
    
</body>
</html>